package com.school.system.config;

import com.alibaba.fastjson2.JSON;
import com.school.system.domain.Announcement;
import com.school.system.mapper.AnnouncementMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: fulin
 * @Date: 2023/03/13/11:17
 * @Description:
 */
@ServerEndpoint("/websocket/taskProcess/{clientId}")
@Component
public class WebSocketServer {

    public static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    public static List<Announcement> PROCESS_INFO = new ArrayList<>();
    public static ConcurrentHashMap<String,WebSocketServer> concurrentHashMap = new ConcurrentHashMap<>();

    private Session session;

    @Resource
    private AnnouncementMapper announcementMapper;

    @PostConstruct
    public void init() {
        Announcement init = Announcement.getInstanceInit();
        List<Announcement> announcements = announcementMapper.selectAnnouncementList(init);
        this.PROCESS_INFO = announcements;
    }

    public void sendMessageNow(String clientId) {
        this.sendMessage(clientId);
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("clientId")String clientId) throws IOException {
        this.session = session;
        concurrentHashMap.put(clientId,this);
        sendMessage(clientId);
    }

    public void sendMessage(@PathParam("clientId")String clientId) {
        WebSocketServer socketServer = concurrentHashMap.get(clientId);
        try {
            socketServer.session.getBasicRemote().sendText(JSON.toJSONString(PROCESS_INFO));
        }catch (Exception e){
            concurrentHashMap.remove(clientId);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("clientId")String clientId) {
        sendMessage(clientId);
    }
}

